package com.xyz.eduservice.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xyz.eduservice.entity.EduSubject;
import com.xyz.eduservice.entity.excel.SubjectData;
import com.xyz.eduservice.entity.vo.SubjectNestedVo;
import com.xyz.eduservice.entity.vo.SubjectVo;
import com.xyz.eduservice.listener.SubjectExcelListener;
import com.xyz.dao.EduSubjectMapper;
import com.xyz.eduservice.service.EduSubjectService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 课程科目 服务实现类
 * </p>
 *
 * @author zsr
 * @since 2021-06-10
 */
@Slf4j
@Service
public class EduSubjectServiceImpl extends ServiceImpl<EduSubjectMapper, EduSubject> implements EduSubjectService {

    //添加课程分类
    @Override
    public void saveSubject(MultipartFile file, EduSubjectService subjectService) {
        try {
            //文件输入流
            InputStream in = file.getInputStream();
            EasyExcel.read(in, SubjectData.class, new SubjectExcelListener(subjectService)).sheet().doRead();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    //获取所有课程分类
    @Override
    public List<SubjectNestedVo> getAllSubject() {
        return getAllSubject(null);
    }

    @Override
    public List<SubjectNestedVo> getAllSubject(Long count) {
        //1. 查询一级分类
        /*QueryWrapper<EduSubject> wrapper1=new QueryWrapper<>();
        wrapper1.eq("parent_id","0");
        //ServiceImpl中注入baseMapper
        List<EduSubject> eduSubjects1 = baseMapper.selectList(wrapper1);

        QueryWrapper<EduSubject> wrapper2=new QueryWrapper<>();
        wrapper2.ne("parent_id","0");
        List<EduSubject> eduSubjects2 = baseMapper.selectList(wrapper2);*/

        //1.流操作
        //查询所有分类

        List<EduSubject> all = this.list();//所有分类
        List<EduSubject> eduSubjects1;
        if(count==null){
            eduSubjects1=all.stream().filter(i -> i.getParentId().equals("0")).collect(Collectors.toList());
        }else{
            eduSubjects1=all.stream().filter(i -> i.getParentId().equals("0")).limit(count).collect(Collectors.toList());
        }
        //一级分类
        List<EduSubject> eduSubjects2 =
                all.stream().filter(i -> !i.getParentId().equals("0")).collect(Collectors.toList());;//二级分类


        return eduSubjects1.stream().map(//一级分类重写map为OneSubject,
                a -> new SubjectNestedVo(a.getId(), "0", a.getTitle(),//OneSubject中的List从eduSubjects2中筛选
                        eduSubjects2.stream().filter(b -> b.getParentId().equals(a.getId()))//filter ParentId等于一级分类的id
                                .map(c -> new SubjectVo(c.getId(), c.getTitle()))//二级分类重写map为TwoSubject
                                .collect(Collectors.toList())))
                .collect(Collectors.toList());
    }

    @Override
    public void addOneSubject(SubjectNestedVo subject) {
        EduSubject entity = new EduSubject();
        entity.setTitle(subject.getTitle());
        
        // 如果传入了parentId且不为空，则使用传入的parentId，否则设置为"0"（根节点）
        if (subject.getParentId() != null && !subject.getParentId().isEmpty()) {
            entity.setParentId(subject.getParentId());
        } else {
            entity.setParentId("0"); // 根节点的parentId为"0"
        }
        
        entity.setSort(0);
        this.baseMapper.insert(entity);

        // 如果有子节点，则添加子节点
        if (subject.getChildren() != null && !subject.getChildren().isEmpty()) {
            String parentId = entity.getId();
            subject.getChildren().forEach(i -> {
                EduSubject c = new EduSubject();
                c.setTitle(i.getTitle());
                c.setParentId(parentId);
                c.setSort(0);
                this.baseMapper.insert(c);
            });
        }
    }
    
    @Override
    public boolean removeSubjectById(String id) {
        log.info("开始删除课程分类，ID: {}", id);
        
        // 先查询该分类是否存在
        EduSubject subject = this.getById(id);
        if (subject == null) {
            log.warn("未找到要删除的课程分类，ID: {}", id);
            return false;
        }
        
        log.info("找到要删除的课程分类，ID: {}, 标题: {}, 父级ID: {}", 
                 subject.getId(), subject.getTitle(), subject.getParentId());
        
        // 如果是一级分类，需要先删除其下的所有二级分类
        if ("0".equals(subject.getParentId())) {
            log.info("该分类是一级分类，正在删除其下的所有二级分类");
            QueryWrapper<EduSubject> wrapper = new QueryWrapper<>();
            wrapper.eq("parent_id", id);
            long count = this.count(wrapper);
            log.info("找到 {} 个二级分类需要删除", count);
            this.remove(wrapper);
            log.info("二级分类删除成功");
        }
        
        // 删除该分类本身
        boolean result = this.removeById(id);
        if (result) {
            log.info("课程分类删除成功，ID: {}", id);
        } else {
            log.error("课程分类删除失败，ID: {}", id);
        }
        return result;
    }
}